package com.cxyzy.myapplication

import android.media.MediaPlayer
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private lateinit var mediaPlayer: MediaPlayer
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        startBtn.setOnClickListener {
            playFromAssets()
            stopBtn.isEnabled = true
            startBtn.isEnabled = false
        }

        stopBtn.setOnClickListener {
            mediaPlayer.stop()
            stopBtn.isEnabled = false
            startBtn.isEnabled = true
        }
    }

    /**
     * 播放assets目录下文件
     */
    private fun playFromAssets() {
        val fd = assets.openFd("test.wav")
        mediaPlayer = MediaPlayer()
        mediaPlayer.setDataSource(fd.fileDescriptor, fd.startOffset, fd.length)
        mediaPlayer.prepare()
        mediaPlayer.start()
    }







    /**
     * 播放URL对应文件
     *
     * 如果希望反复重用同一个MediaPlayer，可以在setDataSource前调用：stop()和reset()
     */
    private fun playFromUrl() {
        val audioUrl = "http://downsc.chinaz.net/Files/DownLoad/sound1/201905/11509.wav"     //这里给一个歌曲的网络地址就行了
        mediaPlayer = MediaPlayer()
        mediaPlayer.setDataSource(audioUrl)
        mediaPlayer.prepareAsync()
        mediaPlayer.setOnPreparedListener { mp -> mp.start() }
    }

    /**
     * 播放raw目录下文件
     */
    private fun playFromRaw() {
        mediaPlayer = MediaPlayer.create(this, R.raw.test)
        mediaPlayer.start()
    }

    /**
     * 播放SD卡上文件
     * 需要动态申请SD读权限
     */
    private fun playFromSdCard() {
        val path = "/sdcard/test.mp3"
        mediaPlayer = MediaPlayer()
        mediaPlayer.setDataSource(path)
        mediaPlayer.prepare()
        mediaPlayer.start()
    }
}